'use strict';
'require view';
'require ui';
'require form';
'require rpc';
'require tools.widgets as widgets';

var formData = {
};
var callServiceList = rpc.declare({
	object: 'service',
	method: 'list',
	params: ['name'],
	expect: {
		'': {}
	}
});
/**Entry Setting */
var callSetLoraAddr = rpc.declare({
    object: 'sihan.energy',
    method: 'set_addr',
    params: ['addr', 'group_addr'],
    expect: {}
});
var callReSetLora = rpc.declare({
    object: 'sihan.energy',
    method: 'reset',
    params: [],
    expect: {}
});
var callGetLoraAddr = rpc.declare({
    object: 'sihan.energy',
    method: 'query_addr',
    params: [],
    expect: {}
});

var callSetLoraTransAddr = rpc.declare({
    object: 'sihan.energy',
    method: 'set_trans',
    params: ['mode','addr','type'],
    expect: {}
});
var callSetLoraPwr = rpc.declare({
    object: 'sihan.energy',
    method: 'set_pwr',
    params: ['pwr'],
    expect: {}
});
var callGetLoraPwr = rpc.declare({
    object: 'sihan.energy',
    method: 'query_pwr',
    params: [],
    expect: {}
});
var callSetLoraBps = rpc.declare({
    object: 'sihan.energy',
    method: 'set_bps',
    params: ['type','bps'],
    expect: {}
});
var callGetLoraBps = rpc.declare({
    object: 'sihan.energy',
    method: 'query_bps',
    params: [],
    expect: {}
});
var callSetLoraLp = rpc.declare({
    object: 'sihan.energy',
    method: 'set_lp',
    params: ['lp'],
    expect: {}
});
var callGetLoraLp = rpc.declare({
    object: 'sihan.energy',
    method: 'query_lp',
    params: [],
    expect: {}
});
var callSetLoraCell = rpc.declare({
    object: 'sihan.energy',
    method: 'set_cell',
    params: ['id'],
    expect: {}
});
var callGetLoraCell = rpc.declare({
    object: 'sihan.energy',
    method: 'query_cell',
    params: [],
    expect: {}
});
var callGetLoraTrans = rpc.declare({
    object: 'sihan.energy',
    method: 'query_trans',
    params: [],
    expect: {}
});
var callSetSleepTime = rpc.declare({
    object: 'sihan.energy',
    method: 'set_sleep',
    params: ['hours','minutes','seconds'],
    expect: {}
});
var callGetEntryInfo = rpc.declare({
    object: 'sihan.energy',
    method: 'query_timeinfo',
    params: [],
    expect: {}
});
var callSetWorkTime = rpc.declare({
    object: 'sihan.energy',
    method: 'set_work',
    params: ['hours','minutes','seconds'],
    expect: {}
});
var callSetLocaltime = rpc.declare({
    object: 'luci',
    method: 'setLocaltime',
    params: ['localtime'],
    expect: {
        result: 0
    }
});
var callSynTime = rpc.declare({
    object: 'sihan.energy',
    method: 'sync_timer',
    params: [],
    expect: {
        result: 0
    }
});
var callControlWork = rpc.declare({
    object: 'sihan.energy',
    method: 'control_work',
    params: [],
    expect: {
        result: 0
    }
});
var callControlSleep = rpc.declare({
    object: 'sihan.energy',
    method: 'control_sleep',
    params: [],
    expect: {
        result: 0
    }
});
function setParams(o, params) {
	if (!params) return;
	for (var key in params) {
		var val = params[key];
		if (key === 'values') {
			for (var j = 0; j < val.length; j++) {
				var args = val[j];
				if (!Array.isArray(args))
					args = [args];
				o.value.apply(o, args);
			}
		} else if (key === 'depends') {
			if (!Array.isArray(val))
				val = [val];
			for (var j = 0; j < val.length; j++) {
				var args = val[j];
				if (!Array.isArray(args))
					args = [args];
				o.depends.apply(o, args);
			}
		} else {
			o[key] = params[key];
		}
	}
	if (params['datatype'] === 'bool') {
		o.enabled = 'true';
		o.disabled = 'false';
	}
}
function defTabOpts(s, t, opts, params) {
	for (var i = 0; i < opts.length; i++) {
		var opt = opts[i];
		var o = s.taboption(t, opt[0], opt[1], opt[2], opt[3]);
		setParams(o, opt[4]);
		setParams(o, params);
	}
}

function getServiceStatus() {
	return L.resolveDefault(callServiceList('idc_energy'), {})
		.then(function(res) {
			var isRunning = false;
			try {
				isRunning = res['idc_energy']['instances']['instance1']['running'];
			} catch (e) {}
			return isRunning;
		});
}
function renderStatus(isRunning) {
	var renderHTML = "";
	var spanTemp = '<em><span style="color:%s"><strong>%s %s</strong></span></em>';
	if (isRunning) {
		renderHTML += String.format(spanTemp, 'green', _("电源服务"), _("RUNNING"));
	} else {
		renderHTML += String.format(spanTemp, 'red', _("电源服务"), _("NOT RUNNING"));
	}
	return renderHTML;
}
/**
 * 将十进制数字转换为4位十六进制字符串
 * @param {number} decimal - 十进制数字
 * @returns {string} 4位十六进制字符串
 */
function decimalToHex4(decimal) {
    if(!decimal){
        return '0000';
    }
    // 将十进制转换为十六进制
    let hex = decimal.toString(16).toUpperCase();
    
    // 补零到4位长度
    return hex.padStart(4, '0');
}
function formatTime(epoch) {
    var date = new Date(epoch * 1000);
    return '%04d-%02d-%02d %02d:%02d:%02d'.format(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
var CBIEntryTime = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var date_time = this.cfgvalue(section_id);
        return E([], [E('input', {
            'id': 'localtime',
            'type': 'text',
			'style': "margin-right:15px",
            'readonly': true,
            'value': date_time
        }), E('button', {
            'class': 'cbi-button cbi-button-apply',
            'click': ui.createHandlerFn(this,
            function() {
                return Promise.all([callSetLocaltime(Math.floor(Date.now() / 1000)), callSynTime()]);
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('Sync with browser')), ' ']);
    },
});
var CBIEntryRunTime = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var run_time = this.cfgvalue(section_id);
        return E('input', {
            'id': 'localtime',
            'type': 'text',
			'style': "margin-right:15px",
            'readonly': true,
            'value': run_time
        });
    },
});
var CBILoraAddr = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var lora_addr = this.cfgvalue(section_id).addr;
		var lora_group = this.cfgvalue(section_id).group_addr;
        return E([], [
            E('input', {
                'id': 'lora_addr',
                'type': 'text',
                'style': "width:98px;margin-right:15px",
                'placeholder': 'LoRa地址',
                'value': decimalToHex4(lora_addr)
            }), 
            E('input', {
                'id': 'lora_group',
                'type': 'text',
                'style': "width:98px;margin-right:15px",
                'placeholder': 'LoRa组播地址',
                'value': decimalToHex4(lora_group)
            }), 
            E('button', {
                'class': 'cbi-button cbi-button-apply',
                'style': "margin-right:15px",
                'click': ui.createHandlerFn(this,
                function() {
                    var lora_addr_value = document.querySelector('input[id="lora_addr"]').value;
                    var lora_group_value = document.querySelector('input[id="lora_group"]').value;
                    return Promise.all([callSetLoraAddr(lora_addr_value, lora_group_value)]);
                }),
                'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
            }, _('保存配置')), 
            E('button', {
                'class': 'cbi-button cbi-button-apply',
                'click': ui.createHandlerFn(this,
                function() {
                    return callReSetLora();
                }),
                'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
            },
            _('重启LoRa模块'))
        ]);
    },
});
var CBILoraTrans = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var trans_addr = this.cfgvalue(section_id).trans_addr;
        return E([], [E('input', {
            'id': 'lora_trans',
            'type': 'text',
			'style': 'margin-right:15px',
			'placeholder': 'LoRa Trans ADDR',
            'value': decimalToHex4(trans_addr)
        }), E('button', {
            'class': 'cbi-button cbi-button-apply',
            'click': ui.createHandlerFn(this,
            function() {
				var lora_trans_value = document.querySelector('input[id="lora_trans"]').value;
                return callSetLoraTransAddr(0, lora_trans_value, 0);
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('保存配置')), ' ']);
    },
});
var CBILoraCfgNuber = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var old_val = this.cfgvalue(section_id);
        return E([], [E('input', {
            'id': this.id,
            'type': 'text',
			'style': 'margin-right:15px',
			'placeholder': this.placeholder,
            'value': old_val
        }), E('button', {
            'class': 'cbi-button cbi-button-apply',
            'click': ui.createHandlerFn(this,
            function() {
				var new_value = document.querySelector('input[id="'+this.id+'"]').value;
				let val_int = parseInt(new_value); // 59
                return this.onClick(val_int);
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('保存配置'))]);
    },
});
var CBIWorkSleep = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
		var time_value = this.cfgvalue(section_id);
        return E([], [E('input', {
            'id': this.id,
            'type': 'text',
			'placeholder': this.placeholder,
			'style': 'margin-right:15px',
            'value': time_value
        }),E('button', {
            'class': 'cbi-button cbi-button-apply',
            'click': ui.createHandlerFn(this,
            function() {
				var time_val = document.querySelector('input[id="'+this.id+'"]').value;
				let timeArray = time_val.split(':');
				// 将数组中的字符串元素分别转换为整数，赋值给时、分、秒变量
				let hours = parseInt(timeArray[0], 10);   // 23
				let minutes = parseInt(timeArray[1], 10); // 59
				let seconds = parseInt(timeArray[2], 10); // 59
				return this.onClick(hours, minutes, seconds);
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('保存配置'))]);
    },
});
var CBIWorkSleepCtrl = form.DummyValue.extend({
    renderWidget: function(section_id, option_id) {
        return E([], [E('button', {
            'class': 'cbi-button cbi-button-apply',
            'style': 'margin-right:15px',
            'click': ui.createHandlerFn(this,
            function() {
				return callControlWork();
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('手动唤醒')),
        E('button', {
            'class': 'cbi-button cbi-button-apply',
            'click': ui.createHandlerFn(this,
            function() {
				return callControlSleep();;
            }),
            'disabled': (this.readonly != null) ? this.readonly: this.map.readonly
        },
        _('手动休眠'))]);
    },
});
return view.extend({
    load: function() {
        return Promise.all([callGetEntryInfo(),callGetLoraTrans(),callGetLoraAddr(),callGetLoraBps(),callGetLoraCell(),callGetLoraLp(),callGetLoraPwr()]);;
    },
	openCannel: function(param){
	},
    render:function(data){
        var m,s,o;
		//m = new form.JSONMap(formData, _('Router Password'), _('Changes the administrator password for accessing the device'));
        m=new form.Map('idc_energy','电源模块设置');
        s = m.section(form.NamedSection, '_status');
		s.anonymous = true;
		s.render = function(section_id) {
			L.Poll.add(function() {
				return L.resolveDefault(getServiceStatus())
					.then(function(res) {
						var view = document.getElementById("service_status");
						view.innerHTML = renderStatus(res);
					});
			});
			return E('div', {
				class: 'cbi-map'
			}, E('fieldset', {
				class: 'cbi-section'
			}, [E('p', {
				id: 'service_status'
			}, _('Collecting data ...'))]));
		}
        s = m.section(form.NamedSection, 'energy', 'conf');
        s.anonymous = true;
        s.addremove = false;
        s.tab("general",  _("电源参数配置")) ;
        s.taboption("general", form.Flag, "is_center", "中心站", "");
        //两个参数，分别是rip和rport
        o = s.taboption('general', CBIEntryRunTime, '_entryruntime', _('电源模块运行时长'));
        o.cfgvalue = function() {
            return data[0].run_time
        };
		o = s.taboption('general', CBILoraAddr, '_addr_button', _('LoRa地址'));
		o.cfgvalue = function(){
			return data[2];
		}
		o = s.taboption('general', CBILoraTrans, '_trans_button', _('LoRa透传地址'));
		o.cfgvalue  = function(){
			return data[1];
		}
		o = s.taboption('general', CBILoraCfgNuber, '_lp_button', _('LoRa工作模式'));
		o.cfgvalue  = function(){
			return data[5].lp;
		}
		o.id="lora_lp";
		o.placeholder="LoRa工作模式"
		o.onClick = function(lp){
			return callSetLoraLp(lp);
		}
		
		o = s.taboption('general', CBILoraCfgNuber, '_pwr_button', _('LoRa发射功率'));
		o.cfgvalue  = function(){
			return data[6].pwr;
		}
		o.id="lora_pwr";
		o.placeholder="LoRa发射功率"
		o.onClick = function(pwr){
			return callSetLoraPwr(pwr);
		}

		o = s.taboption('general', CBILoraCfgNuber, '_cell_button', _('LoRa业务编号'));
		o.cfgvalue  = function(){
			return data[4].cell;
		}
		o.id="lora_cell";
		o.placeholder="LoRa业务编号"
		o.onClick = function(cell){
			return callSetLoraCell(cell);
		}

		o = s.taboption('general', CBILoraCfgNuber, '_bps_button', _('LoRa空中速率'));
		o.cfgvalue  = function(){
			return data[3].data_bps;
		}
		o.id="lora_bps";
		o.placeholder="LoRa空中速率"
		o.onClick = function(bps){
			return callSetLoraBps(0, bps);
		}

		o = s.taboption('general', CBIEntryTime, '_entrytime', _('电源模块时间'));
        o.cfgvalue = function() {
            return data[0].date
        };

        

		o = s.taboption('general', CBIWorkSleep, '_work_sleep_button', _('工作时间'));
		o.cfgvalue = function(){
			return data[0].work_time;
		}
		o.placeholder = "工作时间"
		o.id = "work_time"
		o.onClick = function(hours, min, sec){
			return callSetWorkTime(hours,min,sec);
		}
		o = s.taboption('general', CBIWorkSleep, '_set_work_sleep_button', _('休眠时间'));
		o.cfgvalue = function(){
			return data[0].sleep_time;
		}
		o.placeholder = "休眠时间"
		o.id = "sleep_time"
		o.onClick = function(hours, min, sec){
			return callSetSleepTime(hours,min,sec);
		}
        o = s.taboption('general', CBIWorkSleepCtrl, '_ctrl_work_sleep_button', _('休眠唤醒控制'));
        //标签页
        s.tab("mppt_cfg",  "电源串口配置")
        //两个参数，分别是rip和rport
        s.taboption("mppt_cfg", form.Value, "device", "采集串口:", "")
        o = s.taboption("mppt_cfg", form.ListValue, "speed", "波特率:")
        o.value("9600", "9600")
        o.value("57600", "57600")
        o.value("115200", "115200")
        return m.render();
    },
    // handleSaveApply: null,
//    handleSave: null,
//    handleReset: null
});